using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using Impact.Controllers;
using Impact.Model.Objects;
using Impact.Web.Foundation;

namespace Impact.Web.Admin
{
    /// <summary>
    /// code-behind for the Articles listing page 
    /// </summary>
    public partial class Articles : PageBase
    {

        /// <summary>
        /// override of OnLoad to provide startup functionality
        /// </summary>
        protected override void OnLoad(EventArgs e)
        {

            ShowCategoryPanel(false);
            ShowTagsPanel(false);

            base.OnLoad(e);

        }

        /// <summary>
        /// overridden to handling binding on this page
        /// </summary>
        protected override void Bind()
        {
            ArticleCategoryCollection articleCategories = ArticleController.GetAllCategories(false);

            // bind the category DropDownList in the articles repeater
            // articles will only be shown for the category selected in this dropdownlist
            categories.DataSource = articleCategories;
            categories.DataTextField = ArticleCategory.Columns.Name;
            categories.DataValueField = ArticleCategory.Columns.CategoryId;
            categories.DataBind();
            categories.SelectedValue = (string)Session[Article.Columns.CategoryId];

            // bind the category repeater showing all categories
            if (articleCategories.Count > 0)
            {
                articleCategoryList.DataSource = articleCategories;
                articleCategoryList.DataBind();
                articleCategoryList.Visible = true;
            }
            else
            {
                // if there are no categories, change the display
                articleCategoryList.Visible = false;
                categories.Visible = false;
                articleList.Visible = false;
                addArticleButton.Visible = false;
                errorPanel.Visible = true;
                errorLabel.Text = "There are no categories defined for articles.  Please create at least one category.";
                ShowCategoryPanel(true);
                ToggleCategoryAdd(true);
            }

            // bind the article repeater using the currently selected category
            int selectedCategory;
            if (Int32.TryParse(categories.SelectedValue, out selectedCategory))
            {
                ArticleCollection articles = ArticleController.GetCategoryArticles(selectedCategory, false);
                if (articles.Count > 0)
                {
                    articleList.DataSource = articles;
                    articleList.DataBind();
                }
                else
                {
                    // if there are no articles, change the display
                    articleList.Visible = false;
                    errorPanel.Visible = true;
                    errorLabel.Text = "There are no articles in this category.";
                }
            }

            tagsRepeater.DataSource = ArticleController.GetAllTags();
            tagsRepeater.DataBind();

        }


        /// <summary>
        /// event handler for when the user clicks the "create new article" button
        /// forwards to the EditArticle page with the selected category
        /// </summary>
        protected void NewArticleButtonCommand(object sender, CommandEventArgs e)
        {
            Response.Redirect(string.Format("EditArticle.aspx?cid={0}", categories.SelectedValue));
        }

        /// <summary>
        /// executes when the user clicks any button on the list of articles.  this method
        /// uses the command name parameter to choose which action to execute, and the
        /// command argument parameter to pass in the article id to perform the action on
        /// </summary>
        protected void ArticleList_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            int articleId = Int32.Parse(e.CommandArgument.ToString());
            switch (e.CommandName)
            {
                case "delete":
                    ArticleController.DeleteArticle(articleId);
                    break;

                case "toggleEnabled":
                    ArticleController.ToggleEnabled(articleId);
                    break;

                case "preview":
                    Redirect(string.Format("!preview.ashx?articleId={0}", articleId));
                    break;

                case "toggleComments":
                    ArticleController.ToggleArticleCommentsAllowed(articleId);
                    break;

                case "manageComments":
                    Redirect(string.Format("Comments.aspx?aid={0}", articleId));
                    return;

                default:
                    throw new ArgumentException(string.Format("Command not found: {0}", e.CommandName));
            }

            Bind();

        }

        /// <summary>
        /// event handler fired when the user changes the selected article category
        /// </summary>
        protected void Categories_SelectedIndexChanged(object sender, EventArgs e)
        {
            Session[Article.Columns.CategoryId] = categories.SelectedValue;

            Bind();
        }

        /// <summary>
        /// event handler fired when the user clicks any button in the category repeater
        /// </summary>
        protected void CategoryList_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            int categoryId = Int32.Parse(e.CommandArgument.ToString());
            switch (e.CommandName)
            {
                // the user has clicked the delete button
                case "delete":
                    ArticleController.DeleteArticleCategory(categoryId);
                    break;

                // the user has clicked the toggle button for "allow comments"
                case "toggleComments":
                    ArticleController.ToggleCategoryCommentsAllowed(categoryId);
                    break;

                case "toggleRss":
                    ArticleController.ToggleRssAllowed(categoryId);
                    break;

                case "toggleVisible":
                    ArticleController.ToggleCategoryVisible(categoryId);
                    break;

                default:
                    throw new ArgumentException(string.Format("Command not found: {0}", e.CommandName));
            }

            ShowCategoryPanel(true);
            Bind();
        }

        /// <summary>
        /// event handler fired when the user clicks a button in the tags repeater
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        protected void TagList_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            int tagId = Int32.Parse(e.CommandArgument.ToString());
            switch (e.CommandName)
            {
                case "delete":
                    ArticleController.DeleteTag(tagId);
                    break;

                default:
                    throw new ArgumentException(string.Format("Command not found: {0}", e.CommandName));
            }

            ShowTagsPanel(true);
            Bind();
        }
        

        /// <summary>
        /// event handler fired when the user clicks the add category button
        /// </summary>
        protected void AddCategory_Command(object sender, CommandEventArgs e)
        {
            ToggleCategoryAdd(true);
            ShowCategoryPanel(true);
        }

        /// <summary>
        /// event handler fired when the user submits a new category
        /// </summary>
        protected void NewCategorySubmit(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(newCategoryName.Text))
            {
                ArticleController.AddCategory(newCategoryName.Text);
            }

            ToggleCategoryAdd(false);
            Bind();
            ShowCategoryPanel(true);
        }

        /// <summary>
        /// event handler fired when the user cancels creating a new category
        /// </summary>
        protected void NewCategoryCancel(object sender, EventArgs e)
        {
            ToggleCategoryAdd(false);
            ShowCategoryPanel(true);
        }

        /// <summary>
        /// shows or hides the "add category" form controls
        /// </summary>
        /// <param name="show">true to show the "add category" form controls, false to hide</param>
        private void ToggleCategoryAdd(bool show)
        {
            addCategoryButton.Visible = !show;
            newCategoryPanel.Visible = show;
            newCategoryName.Text = string.Empty;
            if( show ) newCategoryName.Focus();
        }

        /// <summary>
        /// Retrieve the number of articles in the given category
        /// </summary>
        protected string GetArticleCount(object dataItem)
        {
            ArticleCategory category = (ArticleCategory)dataItem;
            return string.Format("[{0}]", ArticleController.GetCategoryArticleCount(category.CategoryId));
        }

        /// <summary>
        /// sets the category panel to be open on the next page load
        /// </summary>
        private void ShowCategoryPanel(bool show)
        {
            showCategories.Value = show.ToString();
        }

        private void ShowTagsPanel(bool show)
        {
            showTags.Value = show.ToString();
        }

        /// <summary>
        /// returns a list of pages in the system that are of the 'template' type
        /// </summary>
        protected TemplateCollection GetTemplates()
        {
            return ArticleController.GetTemplates();
        }

        /// <summary>
        /// Event handler for when the user changes the template of a category
        /// </summary>
        protected void CategoryTemplateChanged(object sender, EventArgs e)
        {
            DropDownList template = sender as DropDownList;
            RepeaterItem item = (RepeaterItem)template.Parent;
            ArticleCategoryCollection categoryCollection = ArticleController.GetAllCategories(false);

            // this is not bulletproof, but i can't figure out how to get the category from
            // the repeater
            ArticleCategory editedCategory = categoryCollection[item.ItemIndex];

            editedCategory.TemplateId = Int32.Parse(template.SelectedValue);
            if (editedCategory.TemplateId <= 0)
            {
                editedCategory.TemplateId = null;
            }

            ArticleController.SaveCategory(editedCategory);

            Bind();
            ShowCategoryPanel(true);

        }






    }
}
